import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { createLogger } from '../modules/Logger.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const DATA_DIR = path.resolve(__dirname, '../data/bilibili');
const SUBSCRIPTION_DIR = path.join(DATA_DIR, 'subscriptions');

let pendingCleanGroups = [];

export class InvalidSubscriptionCleaner extends plugin {
  constructor() {
    super({
      name: '无效订阅清理插件',
      dsc: '清理无效群组及空订阅数据',
      event: 'message',
      priority: 1000,
      rule: [
        { reg: "^#皮皮清理无效订阅$", fnc: 'findInvalidByMessage', permission: 'master' },
        { reg: "^#确定删除$", fnc: 'confirmClean', permission: 'master' }
      ]
    });
    // 创建日志实例
    this.logger = createLogger(this.name);
  }

  // ======================== 核心检测逻辑 ========================
  async findInvalidByMessage(e) {
    try {
      // 获取所有群订阅目录
      const subscribedGroups = this.getAllSubscriptionGroups();

      if (subscribedGroups.length === 0) {
        await e.reply('📭 当前没有订阅记录');
        return;
      }

      await e.reply(`🔍 开始扫描 ${subscribedGroups.length} 个订阅群组...`);

      const [invalidGroups, emptyGroups] = await this.detectInvalidGroups(subscribedGroups, e);
      const allInvalidGroups = [...new Set([...invalidGroups, ...emptyGroups])];

      this.handleDetectionResult(e, allInvalidGroups, invalidGroups, emptyGroups);

    } catch (error) {
      this.logger.error(`❌ 检测失败: ${error.message}`);
      await e.reply('❌ 检测过程中发生系统级错误');
    }
  }

  // ======================== 工具方法 ========================
  getAllSubscriptionGroups() {
    return fs.readdirSync(SUBSCRIPTION_DIR)
     .filter(dir => {
        const dirPath = path.join(SUBSCRIPTION_DIR, dir);
        return fs.statSync(dirPath).isDirectory();
      });
  }

  async detectInvalidGroups(groups, e) {
    const invalidGroups = [];
    const emptyGroups = [];
    let checkedCount = 0;

    const progressHandler = setInterval(() => {
      e.reply(`⏳ 已完成 ${checkedCount}/${groups.length} (${Math.round(checkedCount/groups.length*100)}%)`);
    }, 5000);

    try {
      for (const groupId of groups) {
        checkedCount++;
        
        // 优先检测空订阅
        if (this.isEmptySubscriptionGroup(groupId)) {
          emptyGroups.push(groupId);
          this.logger.info(`📭 发现空订阅群组 ${groupId}`);
          continue;
        }

        // 检测群有效性
        if (await this.isInvalidGroup(groupId)) {
          invalidGroups.push(groupId);
          this.logger.info(`❌ 检测到无效群组 ${groupId}`);
        }

        await this.delay(1000); // 降低API压力
      }
    } finally {
      clearInterval(progressHandler);
    }

    return [invalidGroups, emptyGroups];
  }

  isEmptySubscriptionGroup(groupId) {
    const subFile = path.join(SUBSCRIPTION_DIR, groupId, 'subscriptions.json');
    
    try {
      // 文件不存在视为空订阅
      if (!fs.existsSync(subFile)) return true;
      
      // 检查文件内容有效性
      const content = fs.readFileSync(subFile, 'utf-8');
      const subscriptions = JSON.parse(content);
      return !Array.isArray(subscriptions) || subscriptions.length === 0;
    } catch {
      // 文件损坏视为空订阅
      return true;
    }
  }

  async isInvalidGroup(groupId) {
    try {
      await Bot.pickGroup(groupId).sendMsg('直播推送测试消息｛无视｝'); // 零宽字符测试消息
      return false;
    } catch (error) {
      return true; // 任何发送失败都视为无效群组
    }
  }

  // ======================== 结果处理 ========================
  handleDetectionResult(e, allInvalidGroups, invalidGroups, emptyGroups) {
    if (allInvalidGroups.length === 0) {
      e.reply('✅ 所有群组均有效且存在订阅数据');
      return;
    }

    pendingCleanGroups = allInvalidGroups;
    e.reply([
      '⚠️ 发现以下问题群组：',
      ...invalidGroups.map(g => `▮ 失效群组：${g}`),
      ...emptyGroups.map(g => `▮ 空订阅群：${g}`),
      '——————————————',
      '发送 #确定删除 执行清理 (15秒后自动取消)'
    ].join('\n'));

    this.setCleanupTimeout(e);
  }

  setCleanupTimeout(e) {
    setTimeout(() => {
      if (pendingCleanGroups.length > 0) {
        pendingCleanGroups = [];
        e.reply('⏹️ 清理操作已自动取消');
      }
    }, 15000);
  }

  // ======================== 清理确认 ========================
  async confirmClean(e) {
    if (!pendingCleanGroups.length) {
      await e.reply('⚠️ 没有待处理的清理任务');
      return;
    }

    const report = { success: 0, fail: 0 };

    for (const groupId of [...pendingCleanGroups]) {
      try {
        const groupDir = path.join(SUBSCRIPTION_DIR, groupId);
        if (fs.existsSync(groupDir)) {
          fs.rmSync(groupDir, { recursive: true, force: true });
          report.success++;
          this.logger.info(`✅ 已清理群组 ${groupId}`);
        }
      } catch (error) {
        report.fail++;
        this.logger.error(`❌ 清理失败 ${groupId}: ${error.message}`);
      }
    }

    pendingCleanGroups = [];
    await this.sendCleanReport(e, report);
  }

  async sendCleanReport(e, report) {
    const message = [
      '🗑️ 清理完成报告',
      '——————————————',
      `▸ 成功清理: ${report.success} 个群组`,
      `▸ 清理失败: ${report.fail} 个群组`,
      '——————————————',
      '注：仅删除本地数据，不会影响B站直播间状态'
    ];
    await e.reply(message.join('\n'));
  }

  // ======================== 辅助方法 ========================
  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}